'use strict';

angular.module('PP.services', []);

angular.module('PP.services').value('version', '0.1');

angular.module('PP.services').service('newsService', [ '$q', '$timeout', function($q, $timeout) {
	this.news = [ {}, {} ];
	this.DEFAULT_FAIL_RATE = 0.1;
	this.failRate = this.DEFAULT_FAIL_RATE;

	this.getFailRate = function() {
		return this.failRate;
	};

	this.doNotFail = function() {
		this.failRate = 0;
	};

	this.nextRequestWillFail = function() {
		this.previousRate = this.failRate;
		this.failRate = 1;
	};

	this.getNews = function() {
		var deferred = $q.defer();

		$timeout(function() {
			var willFail = Math.random() < this.failRate;

			if (willFail) {
				this._restorePreviousFailRate();
				deferred.reject('Error while connectiong to the server');
			} else {
				deferred.resolve(this.news);
			}

		}.bind(this), 100);

		return deferred.promise;
	};

	this._restorePreviousFailRate = function() {
		this.failRate = (this.previousRate !== null) ? this.previousRate : this.DEFAULT_FAIL_RATE;
	};

} ]);
